const request = require('../../utils/request');

Page({
  data: {
    orders: [],
    dailyStats: [],
    loading: false
  },

  onLoad() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }
    this.loadOrders(userId);
  },

  async loadOrders(userId) {
    this.setData({ loading: true });
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: request.buildUrl(`/api/orders/user/${userId}`),
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${wx.getStorageSync('token')}`
          },
          success: (r) => resolve(r.data),
          fail: reject
        });
      });

      if (res.success && Array.isArray(res.data)) {
        const orders = res.data;
        this.setData({ orders });
        this.buildDailyStats(orders);
      } else {
        this.setData({ orders: [], dailyStats: [] });
      }
    } catch (e) {
      console.error('加载订单统计失败:', e);
      this.setData({ orders: [], dailyStats: [] });
    } finally {
      this.setData({ loading: false });
      this.drawChart();
    }
  },

  buildDailyStats(orders) {
    // 取最近 7 天
    const now = new Date();
    const dayMs = 24 * 60 * 60 * 1000;
    const days = [];
    for (let i = 6; i >= 0; i--) {
      const d = new Date(now.getTime() - i * dayMs);
      const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d
        .getDate()
        .toString()
        .padStart(2, '0')}`;
      days.push({ date: key, count: 0 });
    }

    orders.forEach((o) => {
      const t = o.created_at || o.createdAt;
      if (!t) return;
      const d = new Date(t);
      const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d
        .getDate()
        .toString()
        .padStart(2, '0')}`;
      const item = days.find((x) => x.date === key);
      if (item) item.count += 1;
    });

    this.setData({ dailyStats: days });
  },

  drawChart() {
    const stats = this.data.dailyStats;
    if (!stats || stats.length === 0) return;

    const context = wx.createCanvasContext('orderLineCanvas', this);
    const width = 320;
    const height = 200;
    const padding = 30;

    context.clearRect(0, 0, width, height);

    // 坐标轴
    context.setStrokeStyle('#cccccc');
    context.setLineWidth(1);
    context.beginPath();
    context.moveTo(padding, padding);
    context.lineTo(padding, height - padding);
    context.lineTo(width - padding, height - padding);
    context.stroke();

    const maxCount = Math.max(1, ...stats.map((s) => s.count));
    const stepX = (width - 2 * padding) / Math.max(1, stats.length - 1);
    const chartHeight = height - 2 * padding;

    // 折线
    context.setStrokeStyle('#007acc');
    context.setLineWidth(2);
    context.beginPath();
    stats.forEach((s, idx) => {
      const x = padding + idx * stepX;
      const y = height - padding - (s.count / maxCount) * chartHeight;
      if (idx === 0) context.moveTo(x, y);
      else context.lineTo(x, y);
    });
    context.stroke();

    // 画点
    context.setFillStyle('#007acc');
    stats.forEach((s, idx) => {
      const x = padding + idx * stepX;
      const y = height - padding - (s.count / maxCount) * chartHeight;
      context.beginPath();
      context.arc(x, y, 3, 0, 2 * Math.PI);
      context.fill();
    });

    // x 轴日期标签（只画部分避免太挤）
    context.setFillStyle('#666666');
    context.setFontSize(10);
    stats.forEach((s, idx) => {
      if (stats.length > 7 && idx % 2 === 1) return;
      const x = padding + idx * stepX;
      const y = height - padding + 12;
      const label = s.date.substring(5); // MM-DD
      context.fillText(label, x - 14, y + 8);
    });

    // y 轴最大值标签
    context.fillText(String(maxCount), 4, padding + 4);

    context.draw();
  }
});
